package org.wattdepot.cli;

import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClientException;

/**
 * Executes the power generated/consumed command.
 * 
 * @author Scott Wong and Kelli Sawai
 * 
 */
public class ListPowerTime extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Executes and returns the results of the power generated/consumed command.
   * 
   * @param args The arguments required to execute this method.
   * @return The results of the command.
   */
  public String doCommand(String args) {
    try {
      if (args.matches("power [generated | consumed]+ \\w* timestamp \\S*")) {
        String[] powerInput = args.split(" ");
        String type = powerInput[1];
        String source = powerInput[2];
        String timestamp = powerInput[4];
        XMLGregorianCalendar gTimestamp = toTimestamp(timestamp);
        XMLGregorianCalendar now =
            DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar());
        if (gTimestamp.compare(now) >= 0) {
          return futureTimestampMessage;
        }
        return listPowerTimestamp(type, source, gTimestamp);
      }
      else {
        return "The command you have entered is invalid.";
      }
    }
    catch (WattDepotClientException e) {
      return "An error occured while executing the requested command.";
    }
    catch (Exception e) {
      return "An error occured while executing the requested command.";
    }
  }

  /**
   * Returns the power generated (or consumed) by the source at the given timestamp. The power value
   * is interpolated if there is no corresponding sensor data instance.
   * 
   * @param type If the power was generated or consumed.
   * @param source The source to which the power information is requested
   * @param timestamp XMLGregorianCalendar timestamp
   * @return the power [generated|consumed] by the source
   * @throws WattDepotClientException if an error occurs
   */
  private String listPowerTimestamp(String type, String source,
      XMLGregorianCalendar timestamp) throws WattDepotClientException {
    try {
      if (type.compareToIgnoreCase("generated") == 0) {
        return Double.toString(client.getPowerGenerated(source, timestamp));
      }
      else {
        return Double.toString(client.getPowerConsumed(source, timestamp));
      }
    }
    catch (ResourceNotFoundException e) {
      return resourceMessage;
    }
  }
}
